<template>
  <div class="product-quality-info">
    <div class="product-quality-info-basic">
      <el-row type="flex" justify="space-between" align="middle" class="mb_12">
        <div>
          <span class="cl_59">{{ $t('product.qualityField.qualityInfoStatus') }}：</span><span class="quality-status" v-if="productInfoStatus" :style="fontStyle(productInfoStatus)">{{ productInfoStatusText }}</span>
        </div>
      </el-row>
      <el-row type="flex" class="mb_12" justify="space-between" align="middle">
        <el-button type="plain-third" @click="jumpProductEdit">{{ $t('product.updateStatus') }}</el-button>
        <div class="dynamic" @click="clickDynamicLog">{{ $t('common.product.qualityInfoDynamicLog') }} ></div>
      </el-row>

      <el-progress v-if="isSpeedProgress" :percentage="speedProgress" :stroke-width="8" class="mb_4"></el-progress>

      <el-row type="flex" justify="space-between" align="middle">
        <div class="cl_59">{{ $t('product.qualityField.qualityInfoStartTime') }}：{{ productInfoStartDate }}</div>
        <div class="cl_59">{{ $t('product.qualityField.qualityInfoEndTime') }}：{{ productInfoEndDate }}</div>
      </el-row>
    </div>

    <div class="product-quality-info-service" v-if="isBgiSaas">
      <el-row type="flex" justify="space-between" align="middle" class="mb_12">
        <el-button type="primary" size="mini" v-if="serviceAdd" @click="handleClickNewOrEditServiceItem('new')">{{ $t('product.addService') }}</el-button>
      </el-row>

      <product-service-table ref="productServiceTableRef" :columnFields="columns" :columnData="dataList" :paginationInfo="paginationInfo" @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange" @handleClickNewOrEditServiceItem="handleClickNewOrEditServiceItem" @handleClickDel="handleClickDel" :serviceEdit="serviceEdit" :serviceDelete="serviceDelete"></product-service-table>
    </div>

    <!-- 动态日志弹框 -->
    <quality-info-record ref="productQualityRef" :shareData="shareData"></quality-info-record>

    <!-- 添加编辑服务 -->
    <product-service-dialog ref="productServiceDialogRef" :type="type" :columnFields="columns" @handleSubmit="handleSubmit"></product-service-dialog>
  </div>
</template>
<script>
import { defineComponent, toRefs, reactive, ref, computed, onMounted } from 'vue';
import { getColumnFields } from '@src/modules/productV2/productWarrantyServiceItem/productWarrantyItemListPage/fields.js';

import QualityInfoRecord from '@src/modules/productV2/productView/components/QualityInfoRecord.vue';
import ProductServiceDialog from '@src/modules/productV2/productView/components/ProductServiceDialog.vue';
import ProductServiceTable from '@src/modules/productV2/productView/components/ProductServiceTable.vue';

import { productQualityInfoList, productQualityInfoRemove, productQualityInfoSave, productQualityInfoUpdate } from '@src/api/ProductV2Api.js';

import { MessageBox } from 'element-ui';
/** util */
import moment from 'moment';
import i18n, { t } from '@src/locales';
import { getRootWindow } from '@src/util/dom';
import { toast } from '@src/util/platform';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import { formatDate, FormatTemplate } from 'pub-bbx-utils'

import { fmt_form_date } from '@src/filter/form.js';
export default defineComponent({
  name: 'product-quality-info',
  props: {
    shareData: {
      type: Object,
      default: () => ({}),
    },
    permission: {
      type: Object,
      default: () => ({}),
    }
  },
  components: {
    QualityInfoRecord,
    ProductServiceDialog,
    ProductServiceTable,
  },
  setup(props) {
    const productQualityRef = ref();
    const productServiceTableRef = ref();
    const productServiceDialogRef = ref();

    const columns = getColumnFields();

    let state = reactive({
      paginationInfo: {
        pageNum: 1,
        pageSize: 10,
        totalItems: 0
      },
      dataList: [],
      type: 'new',
    });

    // 服务项目新建权限
    const serviceAdd = computed(() => {
      return props.permission?.WARRANTY_SERVICE_ADD === 3 || false
    })
    // 服务项目编辑权限
    const serviceEdit = computed(() => {
      return props.permission?.WARRANTY_SERVICE_EDIT === 3 || false
    })
    // 服务项目删除权限
    const serviceDelete = computed(() => {
      return props.permission?.WARRANTY_SERVICE_DELETE === 3 || false
    })

    const productInfo = computed(() => {
      return props.shareData?.product || {};
    });

    // 华大基因灰度
    const isBgiSaas = computed(() => {
      const RootWindow = getRootWindow(window);
      return Boolean(RootWindow.grayAuth?.bgiSaas) || false;
    });

    const fontStyle = computed(() => {
      return val => {
        if (val == '保外') {
          return { color: '#FF7A45', background: '#FFF2E8', borderColor: '#FFD8BF' };
        }
        if (val == '保内') {
          return { color: '#36cfc9', background: '#e6fffb', borderColor: '#b5f5ec' };
        }
      };
    });
    // 质保状态
    const productInfoStatus = computed(() => {
      return productInfo.value?.qualityInfoStatus || '';
    });

    const productInfoStatusText = computed(()=>{
      let status = productInfo.value?.qualityInfoStatus || '';
      if(status == '保内'){
        status = t('common.base.warranty')
      }else if(status == '保外'){
        status = t('common.base.surrender')
      }
      return status;
    })

    // 质保开始时间
    const productInfoStartDate = computed(() => {
      return formatDate(productInfo.value?.qualityStartTime || '', FormatTemplate.date);
    });

    const productInfoEndDate = computed(() => {
      return formatDate(productInfo.value?.qualityEndTime || '', FormatTemplate.date);
    });

    // 是否显示进度条
    const isSpeedProgress = computed(() => {
      return productInfoStartDate.value && productInfoEndDate.value;
    });

    // 进度
    const speedProgress = computed(() => {
      // 开始时间大于当前时间 0%

      // 结束时间小于当前时间 100%
      const start = moment(productInfoStartDate.value).valueOf();
      const end = moment(productInfoEndDate.value).valueOf();
      const now = moment().valueOf();

      if (start >= now) return 0;

      if (end <= now) return 100;

      return Math.round(((now - start) / (end - start)) * 100);
    });

    // 获取服务项目列表
    const fetchServiceList = async () => {
      productServiceTableRef.value.listLoading = true;

      try {
        let ret = await productQualityInfoList({
          productId: productInfo.value?.id,
          pageNum: state.paginationInfo.pageNum,
          pageSize: state.paginationInfo.pageSize
        });

        const { success, message, result } = ret || {};

        if (!success) return toast(message, 'error');

        state.dataList = result?.list || [];
        state.paginationInfo.totalItems = result?.total || 0;
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        productServiceTableRef.value.listLoading = false;
      }
    };

    // 切换分页
    const handleCurrentChange = pN => {
      state.paginationInfo.pageNum = pN;
      fetchServiceList();
    };

    const handleSizeChange = (pageSize) => {
      state.paginationInfo.pageSize = pageSize;
      state.paginationInfo.pageNum = 1;
      fetchServiceList();
    }
    // 查看质保变更动态
    const clickDynamicLog = () => {
      productQualityRef.value.dialogVisible = true;
      productQualityRef.value.initializeRecord();
    };

    // 添加/编辑服务项目
    const handleClickNewOrEditServiceItem = (type, val) => {
      state.type = type;
      productServiceDialogRef.value.openDialog();
      if (type === 'edit') {
        productServiceDialogRef.value.form = {
          svcStartTime: fmt_form_date(val.svcStartTime),
          svcEndTime: fmt_form_date(val.svcEndTime),
          ...val,
        };
      }
    };

    const handleSubmit = params => {
      const newParams = {
        serialNumber: params?.svcSerialNumber,
        projectName: params?.svcProjectName,
        timeLimit: params?.timeLimit,
        remark: params?.svcRemark,
        startTime: params?.svcStartTime,
        endTime: params?.svcEndTime,
        productName: productInfo.value?.name,
        customerId: props.shareData?.customer?.id,
        ...params,
      };

      const urlMap = {
        new: productQualityInfoSave,
        edit: productQualityInfoUpdate,
      };

      try {
        urlMap[state.type]({
          productId: productInfo.value.id,
          ...newParams,
        }).then(res => {
          let { result, success, message } = res || {};

          if (!success) return toast(message, 'error');

          productServiceDialogRef.value && productServiceDialogRef.value.handleReset();
          fetchServiceList();
        });
      } catch (err) {
        console.log('error => 添加服务项目', err);
      }
    };
    // 点击删除
    const handleClickDel = ({ id }) => {
      MessageBox.confirm(i18n.t('product.deleteTips'), i18n.t('common.base.toast'), {
        confirmButtonText: i18n.t('common.base.makeSure'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            productQualityInfoRemove([id]).then(res => {
              instance.confirmButtonLoading = false;

              if (!res.success) {
                return toast(res.message, 'error');
              }

              toast(i18n.t('common.base.tip.deleteSuccess'), 'success');

              done();
              state.paginationInfo.pageNum = 1;
              fetchServiceList();
            });
          } else {
            instance.confirmButtonLoading = false;
            done();
          }
        },
      });
    };

    // 跳转产品编辑页面
    const jumpProductEdit = () => {
      let currTabId = window.frameElement.dataset.id;
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductEdit,
        key: productInfo.value.id,
        closeNowPage: true,
        params: `source=productQuality`,
        fromId: currTabId,
      });
    };

    onMounted(() => {
      if (productServiceTableRef.value) {
        fetchServiceList();
      }
    });

    return {
      productQualityRef,
      productServiceTableRef,
      productServiceDialogRef,
      productInfoStatus,
      fontStyle,
      productInfoStartDate,
      productInfoEndDate,
      isSpeedProgress,
      speedProgress,
      ...toRefs(state),
      columns,
      handleCurrentChange,
      handleSizeChange,
      clickDynamicLog,
      handleClickNewOrEditServiceItem,
      handleSubmit,
      handleClickDel,
      jumpProductEdit,
      isBgiSaas,
      serviceAdd,
      serviceEdit,
      serviceDelete,
      productInfoStatusText
    };
  },
});
</script>
<style lang="scss" scoped>
.product-quality-info {
  padding: 12px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  &-basic {
    background-color: #fafafa;
    border-radius: 4px;
    padding: 12px;
    .quality-status {
      padding: 3px 8px;
      font-size: 12px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      border-radius: 11px;
      border-width: 1px;
      border-style: solid;
    }
    .dynamic {
      color: $color-primary-light-6;
      cursor: pointer;
      margin-left: 24px;
    }
  }
  &-service {
    margin-top: 20px;
    &-title {
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
    }
  }
}
.mb_10 {
  margin-bottom: 10px;
}
.cl_59 {
  color: #595959;
}
</style>
